<template>
  <div class="right-wrapper">
    <el-tabs
      v-model="activeName"
      class="demo-tabs"
      @tab-change="handleClick(activeName)"
    >
      <el-tab-pane label="导读" name="introduction">
        <div style="height: calc(100vh - 120px) !important; position: relative">
          <div
            class="keyword"
            :style="{
              height: h + 'px',
              transition: 'height 0.3s ease 0s',
              width: '100%',
              overflow: 'auto',
            }"
            @scroll="handleScroll"
            ref="domRef"
          >
            <div class="backtop" v-show="scrollTopH > 200">
              <el-icon
                size="20"
                @click="backToTop"
                style="transform: rotate(180deg)"
                ><Download
              /></el-icon>
            </div>
            <div
              v-if="activeName === 'introduction'"
              style="width: 98%"
              v-resize="handler"
            >
              <Collapse
                title="关键词"
                :list="words"
                @click-node="searchWord"
              ></Collapse>
              <Text
                title="全文概要"
                type="info"
                :text="summarization.ParagraphSummary"
              ></Text>
              <ArticleTab></ArticleTab>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="脑图" name="mindmap">
        <div></div>
      </el-tab-pane>
      <el-tab-pane label="笔记" name="note">
        <div style="height: calc(100vh - 120px)">
          <Editor
            v-if="activeName === 'note'"
            @onSave="handleSave"
            :content="content"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
    <div
      class="mind"
      :class="[activeName === 'mindmap' && 'show']"
      v-if="activeName === 'mindmap'"
    >
      <course-mini-map
        @on-ready="updateMindMapData"
        m-key="mindmap_key"
        key="mindmap_key"
      />
    </div>
    <div class="add-note" v-if="showAddNoteBtn && activeName === 'note'">
      <el-button type="primary" @click="handleAddToNote">
        同步到个人笔记
      </el-button>
    </div>
    <div
      class="add-note"
      v-if="courseInfo.mind_map_id === 0 && activeName === 'mindmap'"
    >
      <el-button
        type="primary"
        @click="handleAddToNote"
        v-if="mindMapData !== null"
      >
        同步到个人笔记
      </el-button>
    </div>
    <FolderModal v-model="showFolder" @confirm="handleConfirm" />
  </div>
</template>
<script setup lang="ts">
import { nextTick, ref, defineAsyncComponent } from 'vue'
import Collapse from './Collapse.vue'
import Text from './Text.vue'
import ArticleTab from './ArticleTab.vue'
import { Download } from '@element-plus/icons-vue'
import useCourseStore from '@/stores/course'
import { storeToRefs } from 'pinia'
import CourseMiniMap from '@/views/course-analysis/components/CourseMiniMap.vue'
import {
  httpGetContentByKey,
  httpAddNoteToMy,
  httpUpdateNoteContent,
} from '@/api/course'
import { httpCreateNoteRelation, httpDeleteNoteRelation } from '@/api/note'
import FolderModal from './components/FolderModal.vue'
import { ElMessage } from 'element-plus'
const Editor = defineAsyncComponent(
  () => import('@/components/Editor/index.vue'),
)

const emits = defineEmits(['searchWord'])
const activeName = ref('introduction')
const courseStore = useCourseStore()
const { summarization, words, courseInfo } = storeToRefs(courseStore)
const h = ref(1000)
const handler = (value?: any) => {
  if (activeName.value === 'mindmap') {
    return
  }
  const vh =
    window.innerHeight ||
    document.documentElement.clientHeight ||
    document.body.clientHeight
  h.value = vh - 120
}

const scrollTopH = ref(0)
const domRef = ref(null)
const handleScroll = (e) => {
  scrollTopH.value = e.target.scrollTop
}
const backToTop = () => {
  scrollTopH.value = 0
  domRef.value.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}
const searchWord = (word: string) => {
  courseStore.setKeyWords(word)
  courseStore.setShowSearchInput(true)
  nextTick(() => {
    emits('searchWord', true)
  })
}
const handleClick = (name: string) => {
  if (name === 'mindmap') {
    h.value = 0
  } else if (name === 'note') {
    getNoteData()
  }
}
const showAddNoteBtn = ref(false)
const content = ref('')
const associations = ref([])
const noteId = ref()
const getNoteData = async () => {
  const res: any = await httpGetContentByKey({
    task_id: courseInfo.value.task_id,
    file_key: 'NotBook',
    id: courseInfo.value.id,
  })
  if (res) {
    content.value = res.content
    showAddNoteBtn.value = res.can_add_note
    noteId.value = res.note_id
    associations.value = getContentAssociations(res.content)
  }
}
const showFolder = ref(false)
const handleAddToNote = () => {
  showFolder.value = true
}
const handleSave = async (value: string, from: string) => {
  if (value === content.value) {
    return
  }
  if (from) {
    // 添加
    value = value + content.value
  }
  const res = await httpUpdateNoteContent({
    id: courseInfo.value.id,
    content: value,
  })
  if (res) {
    content.value = value
    !from && updateAssociations(value)
  }
}

const mindMapData = ref(null)

const updateMindMapData = (data: any) => {
  mindMapData.value = data
}

const handleConfirm = async (folder: any) => {
  const res = await httpAddNoteToMy({
    folder_id: folder.id,
    id: courseInfo.value.id,
    content:
      activeName.value === 'mindmap' ? JSON.stringify(mindMapData.value) : '',
  })
  if (res) {
    showFolder.value = false
    if (activeName.value === 'mindmap') {
      courseInfo.value.mind_map_id = 1
    } else {
      showAddNoteBtn.value = false
    }
    ElMessage.success('同步成功')
  }
}
defineExpose({
  handleSave,
})
const getContentAssociations = (content) => {
  // 正则表达式匹配<a>标签中的href属性
  const regex = /<a[^>]*href="([^"]*)"[^>]*>/g
  // 匹配所有符合条件的链接
  const ids = []
  let match
  const includes = ['/file/doc/', '/file/mindmap/', '/file/drawio/']
  while ((match = regex.exec(content)) !== null) {
    let str = match[1]
    if (str) {
      includes.forEach((include) => {
        if (str.includes(include)) {
          str = str.endsWith('/') ? str.substring(0, str.length - 1) : str
          const id = parseInt(str.split(include)[1].split('?')[0])
          if (!isNaN(id) && id > 0) {
            ids.push(id)
          }
        }
      })
    }
  }
  return ids
}
const updateAssociations = (result) => {
  const arr = getContentAssociations(result)
  if (arr.sort().join() !== associations.value.sort().join()) {
    arr.forEach((id1) => {
      if (associations.value.indexOf(id1) < 0) {
        httpCreateNoteRelation({
          source_id: noteId.value,
          target_id: id1,
        }).catch(() => null)
      }
    })
    associations.value.forEach((id2) => {
      if (arr.indexOf(id2) < 0) {
        httpDeleteNoteRelation({
          source_id: noteId.value,
          target_id: id2,
        }).catch(() => null)
      }
    })
    associations.value = arr
  }
}
</script>
<style scoped lang="scss">
.right-wrapper {
  position: relative;
  height: 100%;
  padding: 0 0 0 24px;
  .intro {
    max-height: 0;
    transition: all 5s;
    &.show {
      max-height: fit-content;
    }
  }
}
.mind {
  width: calc(100% - 50px);
  height: calc(100vh - 120px);
  position: absolute;
  top: 50px;
  overflow: hidden;
}
.demo-tabs {
  height: 100%;
  :deep(.el-tabs__nav-wrap) {
    &:after {
      background-color: #fff;
    }
  }
  .keyword {
    padding-right: 20px;
    @include scrollBar;
    .backtop {
      position: absolute;
      bottom: 100px;
      right: 30px;
      z-index: 99;
      width: 30px;
      height: 30px;
      color: #fff;
      background-color: #56565e;
      border-radius: 5px;
      display: flex;
      justify-content: center;
      // flex-direction: column;
      cursor: pointer;
      align-items: center;
    }
  }
}

.add-note {
  position: absolute;
  right: 0;
  top: 0;
  height: 40px;
  display: flex;
  align-items: center;
  margin-right: 10px;
}
</style>
